﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using SignalRTest.Hubs;
using SignalRTest.Models;
using System.Diagnostics;
using System.Security.Claims;
using ViewModels;

namespace SignalRTest.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IHubContext<MyHub> _myHub;


        public HomeController(ILogger<HomeController> logger, IHubContext<MyHub> myHub)
        {
            _logger = logger;
            _myHub = myHub;
        }
        /// <summary>
        /// 发送广播消息
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 一对一消息
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public IActionResult PrivateMsg()
        {
            string userId = HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
            string userName = HttpContext.User.FindFirstValue(ClaimTypes.Name);

            var userInfo = new UserInfo(userName, userId);

            return View(userInfo);
        }

        /// <summary>
        ///一对一发送消息
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="message"></param>
        /// <returns></returns>

        [Authorize, HttpPost]
        public async Task<IActionResult> PostData(string userId,string message)
        {
   
            if (!string.IsNullOrWhiteSpace(userId))
                await _myHub.Clients.User(userId).SendAsync("ReceivePrivateMessage", new {message = message });

            return Json(new { code = "success", msg = "发送成功" });
        }




        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}